<?php

namespace tasks;

use herosphp\bean\Beans;
use tasks\interfaces\ITask;
use herosphp\core\Loader;
use PDO;

Loader::import('tasks.interfaces.ITask', IMPORT_CLIENT);

/**
 * 现货牌号导入
 * @author yu
 * @since 16-12-27
 */
class BrandDataTask implements ITask
{

    private $_dayispot_link;
    private $_dayispot_db_array;

    private $_saas_brand_model_array;

    public function __construct()
    {
        $this->_dayispot_db_array = array(
            'db_type' => 'mysql',
            'db_host' => '14.152.90.133',//'172.28.1.3',
            'db_port' => 3306,
            'db_user' => 'SpotSuser',//'root',
            'db_pass' => 'SpotSelect#@monda',//'monda43%-346ujNyu7deJ',
            'db_name' => 'dayi_spot',//dev_dayi_spot
            'db_charset' => 'utf8',
        );

        $this->_saas_brand_model_array['type'] = Loader::model('ProductType');//类型
        $this->_saas_brand_model_array['product'] = Loader::model('Brand');//品名
        $this->_saas_brand_model_array['factory'] = Loader::model('Factory');//厂家
        $this->_saas_brand_model_array['brand'] = Loader::model('Grade');//牌号

    }

    /**
     * 连接数据库
     * @return bool|PDO
     * @throws \herosphp\exception\HeroException
     */
    private function connect($dbname = '')
    {

        if ($this->_dayispot_link != null) return true;
        $_config = $this->_dayispot_db_array;
        $_dsn = "{$_config['db_type']}:host={$_config['db_host']};port={$_config['db_port']};dbname={$dbname}";
        try {
            $this->_dayispot_link = new PDO($_dsn, $_config['db_user'], $_config['db_pass'], array(PDO::ATTR_PERSISTENT => false));
            $this->_dayispot_link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            //设置数据库编码，默认使用UTF8编码
            $_charset = $_config['db_charset'];
            if (!$_charset) $_charset = 'UTF8';
            $this->_dayispot_link->query("SET names {$_charset}");
            $this->_dayispot_link->query("SET character_set_client = {$_charset}");
            $this->_dayispot_link->query("SET character_set_results = {$_charset}");

        } catch (\PDOException $e) {

            E("数据库连接失败" . $e->getMessage());

        }
        return $this->_dayispot_link;
    }

    /**
     * 测试select方法
     * @return bool
     */
    private function select()
    {

        if ($this->_dayispot_link == null) $this->connect();

        $db_name = $this->_dayispot_db_array['db_name'];

        try {
            $_result = $this->_dayispot_link->query("select product_type,product_name,factory_name,brand_number from `{$db_name}`.`brand` where pass=1")->fetchAll(2);

            echo count($_result);

            return $_result;

        } catch (Exception $e) {

            echo "SQL错误:" . $e;
            return false;
        }
    }

    /**
     * 导入
     */
    private function getBrandDataFromDayiSpot()
    {
        $arr = $this->select();

        foreach ($arr as $k => $v) {

            $v = array_map('addslashes', $v);

            if ($v['product_type']) {

                $typeId = $this->insertType($v['product_type']);
            }

            if ($typeId) {

                $productId = $this->insertProduct($v['product_name'], $typeId);

                if ($productId) {

                    $factoryId = $this->insertFactory($v['factory_name'], $typeId, $productId);


                    if ($factoryId) {

                        $brandId = $this->insertBrand($v['brand_number'], $typeId, $productId, $factoryId);
                        tprintOk("【牌号id: {$brandId}】");

                    }
                }
            }

            //break;
        }
    }

    /**
     * 插入类型数据
     * @param $name
     * @return mixed
     */
    private function insertType($name)
    {

        if ($item = $this->_saas_brand_model_array['type']->getItem(array('name' => $name))) {
            tprintOk("类型成功查询{$name}");

            return $item['id'];
        }

        $data = array(
            "name" => $name,
            "pid" => '0',
            "idpath" => ',0',
            "status" => 1,
            "addtime" => myNow(),
            "updatetime" => myNow(),
        );

        tprintOk("类型开始插入{$name}");
        return $this->_saas_brand_model_array['type']->add($data);


    }

    /**
     * 插入品名数据
     * @param $name
     * @param $typeid
     * @return mixed
     */
    private function insertProduct($name, $typeid)
    {
        if ($item = $this->_saas_brand_model_array['product']->getItem(array('name' => $name, "typeid" => $typeid))) {
            tprintOk("产品成功查询{$name}");

            return $item['id'];
        }

        $data = array(
            "name" => $name,
            "typeid" => $typeid,
            "status" => 1,
            "index_show" => 1,
            "addtime" => myNow(),
            "updatetime" => myNow(),
        );
        tprintOk("产品开始插入{$name}");

        return $this->_saas_brand_model_array['product']->add($data);


    }

    /**
     * 插入厂家数据
     * @param $name
     * @param $typeid
     * @param $productid
     * @return mixed
     */
    private function insertFactory($name, $typeid, $productid)
    {

        if ($item = $this->_saas_brand_model_array['factory']->getItem(array('name' => $name, "typeid" => $typeid, "brandid" => $productid))) {
            tprintOk("厂家成功查询{$name}");

            return $item['id'];
        }

        $data = array(
            "name" => $name,
            "typeid" => $typeid,
            "brandid" => $productid,
            "checked" => 1,
            "status" => 1,
            "addtime" => myNow(),
            "updatetime" => myNow(),
        );
        tprintOk("厂家开始插入{$name}");

        return $this->_saas_brand_model_array['factory']->add($data);

    }

    /**
     * 插入牌号数据
     * @param $name 牌号名
     * @param $typeid 类型id
     * @param $productid 品名id
     * @param $facid  厂家id
     */
    private function insertBrand($name, $typeid, $productid, $facid)
    {

        $sql = "Select * From `saas.dasu123.com`.grade Where name='$name' And typeid='$typeid' And brandid='$productid' And facid='$facid' ";

        //使用getItem查询,牌号为"40E529"时，当成数字处理，框架生成的sql语句SELECT * FROM grade WHERE  1   AND  ( `name` =40E529 ).. 执行错误, MySql Error：Invalid datetime format: 1367 Illegal double '40E529' value found during parsing
        if ($items = $this->_saas_brand_model_array['brand']->getDB()->excute($sql)->fetchAll($fetch_style = 2)) {
            tprintOk("牌号成功查询{$name}");

            return $items[0]['id'];
        }

        $data = array(
            "name" => $name,
            "typeid" => $typeid,
            "brandid" => $productid,
            "facid" => $facid,
            "ischecked" => 1,
            "status" => 1,
            "submiter" => 1,
            "checker" => 1,
            "addtime" => myNow(),
            "updatetime" => myNow(),
            "checktime" => myNow(),
        );
        tprintOk("牌号开始插入{$name}");

        return $this->_saas_brand_model_array['brand']->add($data);
    }


    public function run()
    {
        $this->getBrandDataFromDayiSpot();

    }

}


function myNow()
{
    return date('Y-m-d H:i:s');
}